js 迭代器模式优雅处理递归问题

2025-01-24

一、需求

Antd 的嵌套表格组件的数据源有要求:

数据结构修改前后示例

// 处理之前
const categoryList = [
    {
        categoryId: 1,
        name: '1级',
        children: [
            {
                categoryId: 11,
                name: '11级',
                children: [],
            },
        ],
    },
    {
        categoryId: 2,
        name: '2级',
        children: []
    }
]

// 处理之后
const categoryList = [
    {
        value: 1,
        label: '1级',
        children: [
            {
                value: 11,
                label: '11级',
            },
        ],
    },
    {
        value: 2,
        label: '2级',
    }
]

二、迭代器模式优雅实现递归问题

// 数据源
const categoryList = [
    {
        categoryId: 1,
        name: '1级',
        children: [
            {
                categoryId: 11,
                name: '11级',
                children: [],
            },
        ],
    },
    {
        categoryId: 2,
        name: '2级',
        children: []
    }
]

// 迭代器
const iterator = function (arr, cb) {
    for (let i = 0; i < arr.length; i++) {
        cb.call(arr[i], arr[i])
    }
}

// 处理每一项
const changeItem = function (item) {
    item.value = item.categoryId
    item.label = item.name
    delete item.categoryId
    delete item.name

    if (item.children == false) {
        delete item.children
    } else {
        iterator(item.children, changeItem)
    }
}

// 调用迭代器
iterator(categoryList, changeItem)

console.log(JSON.stringify(categoryList, null, 4))

/*
打印:
[
    {
        "children": [
            {
                "value": 11,
                "label": "11级"
            }
        ],
        "value": 1,
        "label": "1级"
    },
    {
        "value": 2,
        "label": "2级"
    }
]
*/

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: